#!/bin/bash

# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ROOT_DIR=`pwd`

SDK_URL="https://gitee.com/link?target=https%3A%2F%2Frepo.huaweicloud.com%2Fopenharmony%2Fos%2F5.0.0-Release%2Fohos-sdk-windows_linux-public.tar.gz"
SDK_SHA512SUM="7e828b95f6b0d2abf18d19757e5873b1bfd4265052798114ebec359cadcbb6a522fb1b0acda091bf0d60db92d311b64ca9400f161d89a2ee3648586ffee65c1b"

OHOS_SDK=ohos-sdk

function prepare_sdk() {

    echo "start prepare sdk #########"

    if [ -f $OHOS_SDK.tar.gz ]
    then
        local sdk_sum=`sha512sum $OHOS_SDK.tar.gz`
        sdk_sum=${sdk_sum:0:128}
        if [ "x$sdk_sum" != "x$SDK_SHA512SUM" ]
        then
            echo "x$sdk_sum"
            echo "x$SDK_SHA512SUM"
            echo "must change SDK!!"
            rm -rf $OHOS_SDK*
        fi
    fi

    if [ ! -d $OHOS_SDK ]
    then
        if [ ! -f $OHOS_SDK.tar.gz ]
        then
            curl -f -L -- "$SDK_URL" > $OHOS_SDK.tar.gz
            if [ $? -ne 0 ]
            then
                rm -f $OHOS_SDK.tar.gz
                echo "download ohos-sdk failed! #######"
                return 1
            fi
        fi
        mkdir $OHOS_SDK
        tar -zxvf $OHOS_SDK.tar.gz -C $OHOS_SDK
        if [ $? -ne 0 ]
        then
            echo "decompress sdk package failed! #####"
            rm -rf $OHOS_SDK $OHOS_SDK.tar.gz
            return 1
        fi

        cd $OHOS_SDK/linux
        for file in `ls ./`
        do
            unzip $file
        done
        cd $ROOT_DIR
    fi

    return 0
}

function prepare_depot_tools() {
    if [ ! -d "depot_tools" ]
    then
        git clone https://gitee.com/zhong-luping/depot_tools.git
        if [ $? -ne 0 ]
        then
            echo "clone depot_tools failed!"
            rm -rf depot_tools
            return 1
        fi
    fi

    return 0
}

function prepare() {

    export PATH=/usr/local/bin:$PATH

    prepare_sdk
    if [ $? -ne 0 ]
    then
        echo "prepare_sdk failed!!"
        return 1
    fi
    prepare_depot_tools
    if [ $? -ne 0 ]
    then
        echo "prepare_depot_tools failed!!"
        return 1
    fi

    return 0
}

prepare $@
exit $?

#eof
